<?php

namespace Kylinlxl\QiniuOss\Http\Controllers;

use Encore\Admin\Layout\Content;
use Illuminate\Routing\Controller;

class QiniuOssController extends Controller
{
    public function getQiniuUpToken()
    {
        $config = config('qiniu-oss');

        $access_key= $config['QINIU_ACCESS_KEY'];      // 请填写您的AccessKeyId。
        $secret_key= $config['QINIU_SECRET_KEY'];     // 请填写您的AccessKeySecret。

        $zone = $config['QINIU_ZONE'];
        $bucket = $config['QINIU_BUCKET'];
        $domain = $config['QINIU_DOMAIN'];
        $path = $config['QINIU_PATH'];

        $callback_url = $config['QINIU_CALLBACK_URL'];
        $callback_body = $config['QINIU_CALLBACK_BODY'];

        $domain = rtrim($domain, '/');

        $ext = $_GET['ext'] ?? 'jpg';
        $ext = ltrim($ext, '.');

        //七牛上传URL
        $upload_url = $this->uploadZone($zone);
        $response = [
            'code' => 0,
            'msg' => 'success',
            'data' => [],
        ];
        if($upload_url === NULL) {
            $response['code'] = 1000;
            $response['msg'] = '上传区域QINIU_ZONE配置错误, 华东区为z0,华北为z1,华南为z2,北美na0,东南亚为as0';
            return $response;
        }

        if(empty($access_key) || empty($secret_key)) {
            $response['code'] = 1000;
            $response['msg'] = 'QINIU_ACCESS_KEY和QINIU_SECRET_KEY配置错误';
            return $response;
        }

        if(empty($bucket)) {
            $response['code'] = 1000;
            $response['msg'] = '请配置QINIU_BUCKET参数';
            return $response;
        }

        $year  = date('Y');
        $month = date('m');
        $day   = date('d');

        //token 一个小时后失效
        $deadline = time() + 3600;

        $key = $path . '/' . $year . '/' . $month . '/' . $day . '/' . md5(microtime(true) . rand(1, 10000)) . '.' . $ext;
        $scope = $bucket . ':' . $key;

        $args['scope'] = $scope;
        $args['deadline'] = $deadline;

        if(!empty($callback_url) && !empty($callback_body)) {
            $args['callbackUrl'] = $callback_url;
            $args['callbackBody'] = $callback_body;
        }

        $encodedFlags = $this->base64_urlSafeEncode(json_encode($args));
        $sign = hash_hmac('sha1', $encodedFlags, $secret_key, true);
        $encodedSign = $this->base64_urlSafeEncode($sign);

        $token = $access_key . ':' . $encodedSign . ':' . $encodedFlags;

        $response['data'] = [
            'token' => $token,
            'expire' => $deadline,
            'domain' => $domain,
            'key' => $key,
            'url' => $domain . '/' . $key,
            'upload_url' => $upload_url,
        ];

        return $response;
    }

    /**
     * 对提供的数据进行urlsafe的base64编码。
     *
     * @param string $data 待编码的数据，一般为字符串
     *
     * @return string 编码后的字符串
     * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64
     */
    protected function base64_urlSafeEncode($data)
    {
        $find = array('+', '/');
        $replace = array('-', '_');
        return str_replace($find, $replace, base64_encode($data));
    }

    /**
     * 对提供的urlsafe的base64编码的数据进行解码
     *
     * @param string $str 待解码的数据，一般为字符串
     *
     * @return string 解码后的字符串
     */
    protected function base64_urlSafeDecode($str)
    {
        $find = array('-', '_');
        $replace = array('+', '/');
        return base64_decode(str_replace($find, $replace, $str));
    }

    /**
     * 上传地址
     * @param $zone
     */
    protected function uploadZone($zone) {
        //上传地址
        $defaultZone = [
            'z0' => 'https://up.qiniup.com',        //华东
            'z1' => 'https://up-z1.qiniup.com',     //华北
            'z2' => 'https://up-z2.qiniup.com',     //华南
            'na0' => 'https://up-na0.qiniup.com',   //北美
            'as0' => 'https://up-as0.qiniup.com',   //东南亚
        ];

        return $defaultZone[$zone] ?? NULL;
    }

}